﻿package  {
	
	import flash.events.*;
	import flash.net.Socket;
	import flash.utils.ByteArray;
	
	public class SocketTCP extends EventDispatcher{

		private var socket:Socket = new Socket();
		public var respuesta:String;

		public function SocketTCP() {
			// constructor code
			socket.addEventListener(Event.CONNECT, onConnect);
			socket.addEventListener(Event.CLOSE, onClose);
			socket.addEventListener(IOErrorEvent.IO_ERROR, onError);
			socket.addEventListener(ProgressEvent.SOCKET_DATA, onResponse);
			socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecError);
		}

		public function conectar(ip:String, puerto:int):void{
			socket.connect(ip, puerto);
		} 

		private function onConnect(e:Event):void
		{
			trace("Conectado");
			dispatchEvent(new Event("onConnect"));
		}

		private function onClose(e:Event):void
		{
			// Security error is thrown if this line is excluded
			socket.close();
		}

		private function onError(e:IOErrorEvent):void
		{
			trace("IO Error: "+e);
		}

		private function onSecError(e:SecurityErrorEvent):void
		{
			trace("Security Error: "+e);
		}

		private function onResponse(e:ProgressEvent):void
		{
			if (socket.bytesAvailable > 0)
			{
				respuesta = socket.readUTFBytes(socket.bytesAvailable);
				trace(socket.readUTFBytes(socket.bytesAvailable));
				dispatchEvent(new Event("onResponse"));
			}
		}

		public function enviarMensaje(mensaje:String):void
		{
			socket.writeUTFBytes(mensaje);
			socket.flush();
		}
	}
}
